package com.test.request;

import java.io.IOException;
import com.alibaba.fastjson.JSONObject;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetRequest {


    OkHttpClient okHttpClient = new OkHttpClient();
    public static final MediaType type = MediaType
            .parse("application/x-www-form-urlencoded;charset=utf-8;application/json");

    //把get请求的入参拼接在一起
    public String MergeParam(String url, JSONObject param) {
        StringBuffer stringBuffer = new StringBuffer(url);
        stringBuffer.append("?");
        boolean isFrist = true;
        for (String key : param.keySet()) {
            if (!isFrist) {
                stringBuffer.append("&");
            } else {
                isFrist = false;
            }
            stringBuffer.append(key);
            stringBuffer.append("=");
            stringBuffer.append(param.get(key));
        }
        url = stringBuffer.toString();
        return url;
    }

    public String get(String url, String param,int typeparam) {

        JSONObject paramHeaderJO = JSONObject.parseObject(param);
        JSONObject headerJO = (JSONObject) paramHeaderJO.get("headers");
//        System.out.println(headerJO);

        String mergeUrl;
        if(typeparam!=1){
            //get请求如果有入参就进行get--ulr的拼接
            JSONObject paramJO = (JSONObject) paramHeaderJO.get("param");
//            System.out.println(paramJO);
            mergeUrl = MergeParam(url, paramJO);
        }else{
            //get请求没有入参，直接把url赋值
            mergeUrl=url;
        }
        //请求body
        okhttp3.Request.Builder requestBuilder = new Request.Builder().url(mergeUrl);

        //遍历添加header
        if (null != headerJO) {
            for (String key : headerJO.keySet()) {
                requestBuilder.addHeader(key, headerJO.getString(key));
            }
        }

        Request request = requestBuilder.build();
        Call call = okHttpClient.newCall(request);
        Response response;
        // request.
        try {
            response = call.execute();
            // System.out.println(response.code());
            return response.body().string();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "异常：请求错误发生";
        }
    }
}
